<?php
namespace App\HttpController\Pudu;

use App\Common\Controller\Rest;
use think\Db;

class MemberRecords extends Rest
{
    public $modelName = 'MemberRecord';   // model 类名称

    public function POSTIndex()
    {
        $this->abort($this->param['type'], ['类型不能为空!']);
        try{
            $model = $this->model('Member');
            $model->startTrans();
            if($this->param['type'] == 3){
                $userInfo = $model->where(['id' => $this->param['userId']])->find();
                $balance = $userInfo['balance'];
                // 提现记录
                $data1 = [
                    'remain' => $balance - $this->param['change'],
                    'change' => -$this->param['change'],
                    'userId' => $this->param['userId'],
                    'username' => $userInfo['username'],
                    'type'   => 3,
                    'remark' => $this->param['remark']
                ];

                // 手续费记录
                $data2 = [
                    'remain' => $balance - $this->param['change'] - $this->charge($this->param['change']),
                    'change' => -$this->charge($this->param['change']),
                    'userId' => $this->param['userId'],
                    'username' => $userInfo['username'],
                    'type'   => 3,
                    'remark' => '提现手续费'
                ];
                $model->where(['id' => $this->param['userId']])->setDec('balance', $this->param['change']);
                Db::table('pudu_members_record')->insertAll([$data1, $data2]);
            }
            $model->commit();
        }catch(\Exception $e){
            $model->rollback();
            $this->error(['msg' =>  $e->getMessage()]);
        }
       
        $this->result();
    }

    /**
     * 获取提现手续费
     */
    private function charge($change)
    {
        $pec = $this->model('PuduConfig')->getDataOfList()['CASH_CHARGE'];
        return $change * $pec / 100;
    }
}
